<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="4">
          <el-button type="primary" @click="addOne()">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 列表 -->
      <el-table :data="tableData" border stripe style="width: 100%">
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row :class="['bdBottom', i1 == 0 ? 'bdTop' : '', 'vcenter']" v-for="(item1, i1) in scope.row.children" :key="item1.id">
              <!-- 一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeTagById(scope.row, item1)"> {{ item1.authName }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级，三级权限 -->
              <el-col :span="19">
                <el-row :class="[i2 != 0 ? 'bdTop' : '', 'vcenter']" v-for="(item2, i2) in item1.children" :key="item2.id">
                  <!-- 二级权限 -->
                  <el-col :span="6">
                    <el-tag type="success" closable @close="removeTagById(scope.row, item2)"> {{ item2.authName }}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag type="warning" closable @close="removeTagById(scope.row, item3)" v-for="item3 in item2.children" :key="item3.id"> {{ item3.authName }}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#"> </el-table-column>
        <el-table-column prop="roleName" label="角色名"> </el-table-column>
        <el-table-column prop="roleDesc" label="角色描叙"> </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" icon="el-icon-edit" @click.native="editOne(scope.row)">编辑</el-button>
            <el-button type="danger" size="mini" icon="el-icon-delete" @click.native="removeOne(scope.row)">删除</el-button>
            <el-button type="warning" size="mini" icon="el-icon-set-up" @click.native="setRightOne(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- <el-pagination @size-change="handleSizeChange"  @current-change="handleCurrentChange"
        :current-page="pageNum" :page-sizes="[10, 20, 30]" :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination> -->
    </el-card>
    <!-- 修改角色弹窗 -->
    <el-dialog :title="type == 'add' ? '添加角色' : '修改角色'" :visible.sync="dialogEditVisible">
      <el-form :model="addForm" ref="addForm" :rules="rules" label-width="80px" :inline="false" size="normal">
        <el-form-item label="用户名" prop="roleName" placeholder="请输入角色名">
          <el-input v-model="addForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描叙" prop="roleDesc" placeholder="请输入角色描叙">
          <el-input type="textarea" v-model="addForm.roleDesc"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit('addForm')">确定</el-button>
          <el-button @click="dialogEditVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 分配权限 -->
    <el-dialog title="分配权限" :visible.sync="dialogSetRigthVisible" @close="setRightDialog()">
      <el-tree :data="rightList" :props="treeProps" show-checkbox node-key="id" default-expand-all :default-checked-keys="defKeys" ref="treeRef"> </el-tree>
      <span slot="footer">
        <el-button type="primary" @click="allotRight">确定</el-button>
        <el-button @click="dialogSetRigthVisible = false">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      pageNum: 1,
      pageSize: 10,
      total: 0,
      tableData: [],
      dialogSetRigthVisible: false, //分配权限
      rightList: [],
      treeProps: {
        //树形控件绑定对象
        children: 'children',
        label: 'authName'
      },
      defKeys: [105], //默认被选中的树形
      dialogEditVisible: false, //修改
      addForm: {
        email: '',
        mobile: ''
      },
      type: '',
      rules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 1, max: 100, message: '长度在 1 到 100 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
    this.getList()
  },
  methods: {
    getList(type) {
      this.$http
        .get('/roles')
        .then(res => {
          res = res.data
          // console.log(res)
          if (res.meta.status == 200) {
            this.tableData = res.data
            // this.total=res.data.total
            //  console.log('tableData',this.tableData)
          } else {
            this.$message({ type: 'error', message: res.meta.msg })
          }
        })
        .catch(err => {
          console.log(err)
        })
    },
    setRightOne(row) {
      //分配权限显示
      this.roleId = row.id
      this.getRights()
      // 递归获取三级权限id
      this.getLeafKeys(row, this.defKeys)
      this.dialogSetRigthVisible = true
    },
    getRights() {
      //获取权限列表，树形
      this.$http
        .get('/rights/tree')
        .then(res => {
          res = res.data
          console.log(res)
          if (res.meta.status == 200) {
            this.rightList = res.data
            //    console.log('rightList',this.rightList)
          } else {
            this.$message({ type: 'error', message: res.meta.msg })
          }
        })
        .catch(err => {
          console.log(err)
        })
    },
    setRightDialog() {
      //关闭时清空默认选中
      this.defKeys = []
    },
    allotRight() {
      //点击分配权限
      const keys = [...this.$refs.treeRef.getCheckedKeys(), ...this.$refs.treeRef.getHalfCheckedKeys()]
      const idStr = keys.join(',')
      const data = {
        rids: idStr
      }
      console.log('data', data)
      this.$confirm(`确定分配权限?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http
          .post(`roles/${this.roleId}/rights`, data)
          .then(res => {
            res = res.data
            // console.log(res)
            if (res.meta.status == 200) {
              this.$message({ type: 'success', message: '更新成功!' })
              this.getList()
              this.dialogSetRigthVisible = false
            } else {
              this.$message({ type: 'error', message: res.meta.msg })
            }
          })
          .catch(err => {
            console.log(err)
          })
      })
    },
    getLeafKeys(node, arr) {
      //是否是三级节点
      if (!node.children) {
        //当前node没有children，则是三级节点
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        this.getLeafKeys(item, arr)
      })
    },
    removeTagById(role, row) {
      //删除单个权限
      console.log('id', row.id)
      const data = {
        id: row.id
      }
      this.$confirm(`确定删除角色${role.roleName}的${row.authName}权限?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http
          .delete(`/roles/${role.id}/rights/${row.id}`, data)
          .then(res => {
            res = res.data
            // console.log(res)
            if (res.meta.status == 200) {
              this.$message({ type: 'success', message: '删除成功!' })
              role.children = res.data
            } else {
              this.$message({ type: 'error', message: res.meta.msg })
            }
          })
          .catch(err => {
            console.log(err)
          })
      })
    },
    addOne() {
      //新增显示
      this.type = 'add'
      this.addForm = {}
      this.dialogEditVisible = true
    },
    editOne(row) {
      //修改显示
      this.type = 'edit'
      this.dialogEditVisible = true
      this.addForm = JSON.parse(JSON.stringify(row))
    },
    onSubmit(formName) {
      //确定
      // console.log('addForm',this.addForm)
      this.$refs[formName].validate(valid => {
        if (valid) {
          if (this.type == 'add') {
            this.addSubmit()
          } else {
            this.editSubmit()
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    addSubmit() {
      //新增用户提交数据
      const data = {
        roleName: this.addForm.roleName,
        roleDesc: this.addForm.roleDesc
      }
      console.log('data', data)
      this.$confirm(`确定提交?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http
          .post(`/roles`, data)
          .then(res => {
            res = res.data
            // console.log(res)
            if (res.meta.status == 201) {
              this.dialogEditVisible = false
              this.$message({ type: 'success', message: res.meta.msg })
              this.getList('1')
            } else {
              this.$message({ type: 'error', message: res.meta.msg })
            }
          })
          .catch(err => {
            console.log(err)
          })
      })
    },
    editSubmit() {
      //修改用户提交数据
      const data = {
        id: this.addForm.id,
        roleName: this.addForm.roleName,
        roleDesc: this.addForm.roleDesc
      }
      console.log('data', data)
      this.$confirm(`确定提交?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http
          .put(`/roles/${this.addForm.id}`, data)
          .then(res => {
            res = res.data
            // console.log(res)
            if (res.meta.status == 200) {
              this.dialogEditVisible = false
              this.$message({ type: 'success', message: '修改成功!' })
              this.getList('1')
            } else {
              this.$message({ type: 'error', message: res.meta.msg })
            }
          })
          .catch(err => {
            console.log(err)
          })
      })
    },
    removeOne(row) {
      //删除用户
      const data = {
        id: row.id
      }
      console.log('data', data)
      this.$confirm(`确定删除角色${row.roleName}?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http
          .delete(`/roles/${row.id}`, data)
          .then(res => {
            res = res.data
            // console.log(res)
            if (res.meta.status == 200) {
              this.getList('1')
              this.$message({ type: 'success', message: '删除成功!' })
            } else {
              this.$message({ type: 'error', message: res.meta.msg })
            }
          })
          .catch(err => {
            console.log(err)
          })
      })
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.pageNum = val
      this.getList()
    }
  }
}
</script>

<style scoped>
.el-tag {
  margin: 7px;
}
.bdTop {
  border-top: 1px solid #ddd;
}
.bdBottom {
  border-bottom: 1px solid #ddd;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
